package tech.daoxuan.web.async;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

@RestController
public class AsyncController {

    Logger logger = LoggerFactory.getLogger(AsyncController.class);

    @Autowired
    private MockQueue mockQueue;

    @Autowired
    private DeferredResultHolder deferredResultHolder;

    @RequestMapping("/order")
    public DeferredResult<String> order() throws InterruptedException {
        logger.info("主线程 开始");

        //随机生成 8 位的订单号
        String orderNumber = RandomStringUtils.randomNumeric(8);

        //把生成的订单号，放置到 消息队列中(模拟)
        mockQueue.setPlaceOrder(orderNumber);


        DeferredResult<String> objectDeferredResult = new DeferredResult<>();
        deferredResultHolder.getMap().put(orderNumber, objectDeferredResult);
//        Callable<String> stringCallable = new Callable<String>() {
//            /**
//             * Computes a result, or throws an exception if unable to do so.
//             *
//             * @return computed result
//             * @throws Exception if unable to compute a result
//             */
//            @Override
//            public String call() throws Exception {
//                logger.info("副线程  开始");
//                Thread.sleep(2000);
//                logger.info("副线程  返回");
//                return "success";
//            }
//        };

        logger.info("主线程  返回");
        //return stringCallable;
        return objectDeferredResult;
    }
}
